import React, { useMemo, useState } from 'react';
import { useI18n } from '@/utils/in18';

// 子组件：我喜欢的作品-详情弹窗
// 功能：
// - 展示大图与信息：image_url、likes_count、display_prompt（以逗号分割的标签渲染）、created_at
// - 操作按钮：“移除喜欢”（二次确认）与“创建图片”（回传给父组件处理跳转）
// - UI：Tailwind；适配明亮/暗黑主题与 PC/移动端

export type LikedWorkForModal = {
  id: number;
  template_id?: number;
  image_url: string;
  likes_count?: number;
  display_prompt?: string;
  created_at?: string;
  role_prompt?: string;
};

type Props = {
  open: boolean; // 是否展示弹窗
  item: LikedWorkForModal | null; // 当前查看的作品
  onClose: () => void; // 关闭弹窗
  onConfirmUnlike: (workId: number) => Promise<void>; // 确认移除喜欢
  onCreateImage: (work: LikedWorkForModal) => void; // 创建图片
};

const LikedWorkModal: React.FC<Props> = ({ open, item, onClose, onConfirmUnlike, onCreateImage }) => {
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const { t } = useI18n();

  // 将 display_prompt 以逗号分割为标签，并为不同标签分配不同背景色（明暗主题）
  const tags = useMemo(() => {
    return String(item?.display_prompt || '')
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean);
  }, [item?.display_prompt]);

  const tagBgClasses = [
    'bg-red-100 dark:bg-red-900',
    'bg-yellow-100 dark:bg-yellow-900',
    'bg-green-100 dark:bg-green-900',
    'bg-blue-100 dark:bg-blue-900',
    'bg-indigo-100 dark:bg-indigo-900',
    'bg-pink-100 dark:bg-pink-900',
    'bg-purple-100 dark:bg-purple-900',
    'bg-emerald-100 dark:bg-emerald-900',
  ];

  const createdStr = item?.created_at ? new Date(item.created_at).toLocaleString() : '';

  // 注意：所有 Hook 已在顶部调用，保证任意渲染周期 Hook 顺序一致
  if (!open || !item) return null;

  return (
    <div className="fixed inset-0 z-[12000] flex items-center justify-center p-4">
      {/* 背景遮罩 */}
      <div className="absolute inset-0 bg-black/60" onClick={onClose} />

      {/* 内容容器 */}
      <div className="relative z-10 w-full max-w-5xl max-h-[90vh] overflow-auto rounded-2xl bg-white dark:bg-[#0b0b0b] text-gray-900 dark:text-gray-100 shadow-2xl border border-gray-200 dark:border-gray-700">
        {/* 头部 */}
        <div className="flex items-center justify-between px-4 sm:px-6 py-3 border-b border-gray-200 dark:border-gray-700">
          <div className="font-semibold">{t('my_work.work_details')}</div>
          <button onClick={onClose} className="px-2 py-1 rounded hover:bg-gray-100 dark:hover:bg-[#111]/60">{t('my_work.close')}</button>
        </div>

        {/* 主体：左右布局（移动端上下） */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-0 md:gap-4 max-h-[calc(90vh-56px)]">
          {/* 图片预览 */}
          <div className="p-4 md:p-6 overflow-auto flex items-center justify-center bg-gray-50 dark:bg-[#0a0a0a]">
            <img src={item.image_url} alt="work" className="max-h-[60vh] md:max-h-[70vh] w-auto rounded-lg object-contain border border-gray-200 dark:border-gray-700" />
          </div>

          {/* 信息与操作 */}
          <div className="p-4 md:p-6 overflow-auto">
            {/* 标签 */}
            <div className="flex flex-wrap gap-2">
              {tags.length > 0 ? (
                tags.map((tag, idx) => (
                  <span key={idx} className={`text-xs px-2 py-1 rounded-full border border-gray-200 dark:border-gray-700 ${tagBgClasses[idx % tagBgClasses.length]}`}>
                    {tag}
                  </span>
                ))
                ) : (
                <span className="text-xs text-gray-500">{t('my_work.no_tags')}</span>
              )}
            </div>

            {/* 信息卡片：时间与点赞 */}
            <div className="mt-4 grid grid-cols-2 gap-3 text-sm">
              <div className="flex flex-col p-3 rounded-lg bg-gray-50 dark:bg-[#0b0b0b] border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2">
                  <svg className="w-4 h-4 text-gray-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 7V12L15 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M21 12A9 9 0 1 1 3 12a9 9 0 0 1 18 0z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  <span className="text-gray-500 text-xs">{t('my_work.creation_time')}</span>
                </div>
                <span className="mt-1">{createdStr}</span>
              </div>
              <div className="flex flex-col p-3 rounded-lg bg-gray-50 dark:bg-[#0b0b0b] border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2">
                  <svg className="w-4 h-4 text-gray-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 1 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z" stroke="currentColor" strokeWidth="0.5" fill="currentColor" />
                  </svg>
                  <span className="text-gray-500 text-xs">{t('my_work.number_of_likes')}</span>
                </div>
                <span className="mt-1">{item.likes_count ?? 0}</span>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="mt-4 flex flex-wrap gap-3">
              <button
                className="px-4 py-2 text-sm rounded-lg border border-red-200 text-red-600 hover:bg-red-50"
                onClick={() => setConfirmOpen(true)}
              >
                {t('my_liked_persion.remove_like')}
              </button>
              <button
                className="px-4 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-[#111]"
                onClick={() => onCreateImage(item)}
              >
                {t('my_liked_persion.create_picture')}
              </button>
            </div>
          </div>
        </div>

        {/* 二次确认弹窗 */}
        {confirmOpen && (
          <div className="fixed inset-0 z-[13000] flex items-center justify-center p-4">
            <div className="absolute inset-0 bg-black/50" onClick={() => (confirmLoading ? null : setConfirmOpen(false))} />
            <div className="relative z-10 w-full max-w-sm rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0b0b0b] p-4 shadow-xl">
              <div className="text-base font-semibold text-gray-900 dark:text-gray-100">{t('my_liked_persion.confirm_title')}</div>
              <div className="mt-2 text-sm text-gray-600 dark:text-gray-300">{t('my_liked_persion.confirm_message')}</div>
              <div className="mt-4 flex justify-end gap-2">
                <button
                  className="px-3 py-1.5 text-sm rounded border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-[#111]"
                  onClick={() => setConfirmOpen(false)}
                  disabled={confirmLoading}
                >
                  {t('my_liked_persion.cancel')}
                </button>
                <button
                  className="px-3 py-1.5 text-sm rounded bg-red-600 text-white hover:opacity-90"
                  onClick={async () => {
                    try {
                      setConfirmLoading(true);
                      await onConfirmUnlike(item.id);
                      setConfirmOpen(false);
                    } finally {
                      setConfirmLoading(false);
                    }
                  }}
                  disabled={confirmLoading}
                >
                  {confirmLoading ? t('my_liked_persion.please_wait') : t('my_liked_persion.confirm')}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default LikedWorkModal;


